package cn.com.twoke.game.server.handler;

import cn.com.twoke.game.common.entity.message.InviteJoinGameMessage;
import cn.com.twoke.game.common.handler.MessageHandler;
import cn.com.twoke.game.common.utils.MessageUtil;
import cn.com.twoke.game.server.cache.GameRoomCache;
import cn.com.twoke.game.server.cache.OnlineUserCache;
import cn.com.twoke.game.server.entity.GameRoom;

import java.io.IOException;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class InviteJoinGameMessageHandler implements MessageHandler<InviteJoinGameMessage> {
    @Override
    public void handle(Selector selector, SocketChannel channel, InviteJoinGameMessage message) throws IOException {
        if (message.getInviteType() == InviteJoinGameMessage.Type.INVITE) {
            GameRoomCache.add(message.getRoomMasterId(),
                    new GameRoom(message.getGameRoomId(), message.getRoomMasterId()));
            // 邀请用户添加到游戏房间
            for (String userId : message.getUserIds()) {
                MessageUtil.writeMessage(OnlineUserCache.get(userId), message);
            }
        } else if (message.getInviteType() == InviteJoinGameMessage.Type.ACCEPT) { // 接受邀请
            GameRoomCache.get(message.getRoomMasterId())
                    .getPlayerIds()
                    .add(message.getInviteUserId());
            MessageUtil.writeMessage(channel, message);
            MessageUtil.writeMessage(OnlineUserCache.get(message.getRoomMasterId()), message);
        } else if (message.getInviteType() == InviteJoinGameMessage.Type.REJECT) { // 拒绝邀请
            MessageUtil.writeMessage(channel, message);
            MessageUtil.writeMessage(OnlineUserCache.get(message.getRoomMasterId()), message);
        }
    }
}
